//获取所有学生信息
function getRoomInfo() {
    $.ajax({
        url: "http://localhost/hotel/php/roomQueryAll.php",
        success(msg) {
            // console.log(msg);
            sessionStorage.setItem("roomInfo", msg)
            sessionStorage.setItem("pageCurrent", 1)
            msg = JSON.parse(msg).slice(0, 10)
            let pageCurrent=sessionStorage.getItem("pageCurrent")
            let getRoomSortMessage1=JSON.parse(sessionStorage.getItem("roomInfo"))
            showPage.innerHTML=`${pageCurrent}/${Math.ceil(getRoomSortMessage1.length/10)}`
            renderRoomInfo(msg);
            

            // 禁用首页
            $("#first").attr("disabled", true)
            $("#first").css("cursor", "not-allowed")
            // 禁用上一页
            $("#prev").attr("disabled", true)
            $("#prev").css("cursor", "not-allowed")
            // //显示当前页数
            // const pageNumber = document.querySelector("#pageNumber")
            // pageNumber.innerHTML = pageCurrent
        }
    })
}
getRoomInfo();

//渲染页面
function renderRoomInfo(msg) {
    $("#rtbody")[0].innerHTML = "";

    msg.forEach(item => {
        let str = `
            <tr>
                <td style="padding-left: 60px;">${item.roomAddress}</td>
                <td>${item.type}</td>
                <td style="padding-left: 15px;">${item.status}</td>
                <td>${item.price}</td>
                <td>
                    <button data-bs-toggle="modal" data-bs-target="#myModalEdit" class='btn btn-warning btn-sm' data-edit='edit' id="${item.roomId}">修改</button>
                    <button style="margin-left:20px" class="btn btn-danger btn-sm" data-del='del' id="${item.roomId}">删除</button>
                </td>
            </tr>
        `
        $("#rtbody")[0].innerHTML += str;
    })
}

//获取房间类型数据渲染下拉模态框
function getRoomtypeInfo() {
    $.ajax({
        url: "http://localhost/hotel/php/roomtypeQueryAll.php",
        success(msg) {
            sessionStorage.setItem("sortInfo", msg)
            msg = JSON.parse(msg)
            // console.log(msg);
            let str = '<option>请选择</option>'
            msg.forEach(item => {
                str += `
                    <option value="${item.rtId}">${item.type}</option>
                `
                $("#roomType").html(str);
            })
        }
    })
}

//添加房间
function addRoomInfo() {

    const roomAddress = $("#roomAddress").val()
    const price = $("#price").val()
    const roomType = $("#roomType").val()
    const roomStatus = $(".roomStatus")
    let status = ''
    if (roomStatus[0].checker == true) {
        status = '未入住'
    } else {
        status = '已入住'
    }
    // console.log(roomAddress,roomType,price,status);
    if (!(roomAddress && roomType && price)) {
        return alert("请输入完整的数据!")
    }

    Ajax({
        type: "POST",
        url: "http://localhost/hotel/php/roomAdd.php",
        data: { roomAddress, roomType, status, price },
        success() {

            location.reload();
        }
    })
}

//所有房间
function renderAllRoomInfo(){
    location.reload();
}

//删除操作,利用事件的委托(委派)
$("#rtbody").click(function (e) {
    e = e || window.event
    // console.log(e.target.id);
    if (e.target.dataset.del == 'del') {
        const flag = window.confirm("您确定要删除吗?")
        if (flag) {
            Ajax({
                url: "http://localhost/hotel/php/roomDelete.php",
                data: { id: e.target.id },
                success() {
                    location.reload();
                }
            })
        }
    }

    //渲染修改点击默认信息
    if (e.target.dataset.edit == 'edit') {
        Ajax({
            url: "http://localhost/hotel/php/roomQueryOne.php",
            data: { id: e.target.id },
            success(msg1) {
                // console.log(msg1);
                msg1 = JSON.parse(msg1)
                $("#updateroomId").val(msg1.roomId);
                $("#updateroomAddress").val(msg1.roomAddress);
                $("#updateroomType").val(msg1.type);
                $("#updatePrice").val(msg1.price);
                if (msg1.status == '未入住') {
                    $(".updateStatus")[0].checked = true;
                } else {
                    $(".updateStatus")[1].checked = true;
                }

                //发送ajax,获取房间类型信息,渲染房间类型数据
                Ajax({
                    url: "http://localhost/hotel/php/roomtypeQueryAll.php",
                    success(msg) {
                        // console.log(msg);
                        //将数据存储到storage
                        sessionStorage.setItem("roomtypeInfo", msg)
                        //将类型数据渲染到类型的表单当中
                        msg = JSON.parse(msg)
                        //渲染页面
                        $("#updateroomType").html("<option>请选择</option>");
                        //房间类型
                        let str = ``
                        msg.forEach(item => {
                            //当学生信息里面的班级ID等于下拉框里面的班级ID的时候,那么默认要显示这个班也就是个这个班加上 selected
                            // console.log(msg1.roomType, item.type);
                            if (msg1.roomType == item.rtId) {
                                str += `<option selected value="${item.rtId}">${item.type}</option>`
                            } else {
                                str += `<option value="${item.rtId}">${item.type}</option>`
                            }
                            $("#updateroomType").html(str)
                        })
                    }
                })
            }
        })
    }


})
//确定修改按钮
function updateRoomInfo() {
    const updateroomId = $("#updateroomId").val();
    const updateroomAddress = $("#updateroomAddress").val()
    const updateroomType = $("#updateroomType").val()
    const updatePrice = $("#updatePrice").val()
    const updateStatus = $(".updateStatus");
    let status = ''
    
    if (updateStatus[0].checked == true) {
        status = '未入住'
    } else {
        status = '已入住'
    }
    
    if (!(updateroomAddress && updateroomType && updatePrice)) {
        return alert("请输入完整的数据!")
    }
    Ajax({
        type: "POST",
        url: "http://localhost/hotel/php/roomUpdate.php",
        data: { updateroomAddress, status, updatePrice, updateroomType, updateroomId },

        success() {
            location.reload();
        }
    })

}

/* 
    首页
*/
function first() {
    // sessStorage里面存储的pageCurrent = 1
    sessionStorage.setItem("pageCurrent", 1)
    // 从storage里面获取所有的学生数据,渲染前10条
    // 禁用首页
    $("#first").attr("disabled", true)
    $("#first").css("cursor", "not-allowed")
    // 禁用上一页
    $("#prev").attr("disabled", true)
    $("#prev").css("cursor", "not-allowed")
    //解除下一页禁用
    $("#next").css("cursor", "auto")
    $("#next").attr("disabled", false)
    //解除尾页禁用
    $("#last").css("cursor", "auto")
    $("#last").attr("disabled", false)
    let roomInfo = sessionStorage.getItem("roomInfo")
    let pageCurrent = sessionStorage.getItem("pageCurrent")
    let getRoomSortMessage1=JSON.parse(sessionStorage.getItem("roomInfo"))
    showPage.innerHTML=`${pageCurrent}/${Math.ceil(getRoomSortMessage1.length/10)}`
    // 将JSON数据转换成对象
    roomInfo = JSON.parse(roomInfo)

    //获取前10条数据,准备渲染页面
    roomInfo = roomInfo.slice(0, 10)
    //调用函数,渲染页面
    renderRoomInfo(roomInfo);
}

/* 
    尾页
*/
function last() {
    // 禁用尾页
    $("#last").attr("disabled", true)
    $("#last").css("cursor", "not-allowed")
    // 禁用下一页
    $("#next").attr("disabled", true)
    $("#next").css("cursor", "not-allowed")
    //解除首页的禁用
    $("#first").css("cursor", "auto")
    $("#first").attr("disabled", false)
    //解除上一页的禁用
    $("#prev").css("cursor", "auto")
    $("#prev").attr("disabled", false)

    //1. 获取所有的学生数据
    let roomInfo = sessionStorage.getItem("roomInfo")
    //2. 计算总共有多少页
    roomInfo = JSON.parse(roomInfo)
    let getRoomSortMessage1=JSON.parse(sessionStorage.getItem("roomInfo"))
    const pageCurrent = Math.ceil(roomInfo.length / 10)
    //3. 将总共的页存储到storage里面
    sessionStorage.setItem("pageCurrent", pageCurrent)
    //4. 获取后10条数据,准备渲染页面

    //将最后一页的数据计算出来
    if (roomInfo.length % 10 != 0) {
        roomInfo = roomInfo.slice(Math.floor(roomInfo.length / 10) * 10, roomInfo.length)
    } else {
        roomInfo = roomInfo.slice(Math.floor(roomInfo.length / 10 - 1) * 10, roomInfo.length)
    }
    showPage.innerHTML=`${pageCurrent}/${Math.ceil(getRoomSortMessage1.length/10)}`
    //渲染页面
    renderRoomInfo(roomInfo)
}

/* 
    上一页
*/
function up() {
    // 1. 获取当前页
    let pageCurrent = +sessionStorage.getItem("pageCurrent")
    
    // 2. 当前页-1 不能小于1,如果小于,那么就等于1
    pageCurrent = pageCurrent - 1
    if (pageCurrent <= 1) {
        pageCurrent = 1;
        //禁用首页
        $("#first").attr("disabled", true)
        $("#first").css("cursor", "not-allowed")
        // 禁用上一页
        $("#prev").attr("disabled", true)
        $("#prev").css("cursor", "not-allowed")
        //解除下一页禁用
        $("#next").css("cursor", "auto")
        $("#next").attr("disabled", false)
        //解除尾页禁用
        $("#last").css("cursor", "auto")
        $("#last").attr("disabled", false)
    } else {
        //解除首页的禁用
        $("#first").css("cursor", "auto")
        $("#first").attr("disabled", false)
        //解除下一页禁用
        $("#next").css("cursor", "auto")
        $("#next").attr("disabled", false)
        //解除尾页禁用
        $("#last").css("cursor", "auto")
        $("#last").attr("disabled", false)
    }
    //存储当前页
    sessionStorage.setItem("pageCurrent", pageCurrent)
    //获取上一页的数据
    let roomInfo = sessionStorage.getItem("roomInfo")
    let getRoomSortMessage1=JSON.parse(sessionStorage.getItem("roomInfo"))
    //将JSON转换成对象
    roomInfo = JSON.parse(roomInfo)
    roomInfo = roomInfo.slice((pageCurrent - 1) * 10, pageCurrent * 10)
    // console.log(roomInfo);
    showPage.innerHTML=`${pageCurrent}/${Math.ceil(getRoomSortMessage1.length/10)}`
    //渲染数据
    renderRoomInfo(roomInfo)
}

/* 
    下一页
*/
function down() {
    // 1. 获取当前页
    let pageCurrent = +sessionStorage.getItem("pageCurrent")
    pageCurrent = pageCurrent + 1
    //获取所有的学生信息
    let roomInfo = JSON.parse(sessionStorage.getItem("roomInfo"))
    // 2. 计算最后一页
    let lastPage = Math.ceil(roomInfo.length / 10)
    // 当前页+1,当前页不能大于最后一页
    if (pageCurrent >= lastPage) {
        pageCurrent = lastPage
        // 禁用尾页
        $("#last").attr("disabled", true)
        $("#last").css("cursor", "not-allowed")
        // 禁用下一页
        $("#next").attr("disabled", true)
        $("#next").css("cursor", "not-allowed")
        //解除首页的禁用
        $("#first").css("cursor", "auto")
        $("#first").attr("disabled", false)
        //解除上一页的禁用
        $("#prev").css("cursor", "auto")
        $("#prev").attr("disabled", false)
    } else {
        //解除首页的禁用
        $("#first").css("cursor", "auto")
        $("#first").attr("disabled", false)
        //解除上一页的禁用
        $("#prev").css("cursor", "auto")
        $("#prev").attr("disabled", false)
        //解除尾页禁用
        $("#last").css("cursor", "auto")
        $("#last").attr("disabled", false)
    }
    //存储当前页
    sessionStorage.setItem("pageCurrent", pageCurrent)
    let getRoomSortMessage1=JSON.parse(sessionStorage.getItem("roomInfo"))
    // 获取当前页的数据
    roomInfo = roomInfo.slice((pageCurrent - 1) * 10, pageCurrent * 10)
    showPage.innerHTML=`${pageCurrent}/${Math.ceil(getRoomSortMessage1.length/10)}`
    //渲染学生信息
    renderRoomInfo(roomInfo)
}

// 输入房间号查询  首位模糊查询
function queryLikeAddress(){
    const likeAddress = $("#likeAddress").val()
    if (likeAddress.trim().length == 0) {
        return alert("请输入楼层")
    }
    Ajax({
        url: "http://localhost/hotel/php/roomFindLikeAddress.php",
        data: { address:likeAddress },
        success(msg) {
            if (msg == '[]') {
                alert("查无此房!")
                $("#likeName").val("")
            } else {
                //将数据存储到Storage里面
                sessionStorage.setItem("roomInfo", msg)
                //将msg转化对象
                let roomInfo = JSON.parse(msg)
                //获取前10条数据
                roomInfo = roomInfo.slice(0, 10)
                //当前页是第一页
                sessionStorage.setItem("pageCurrent", 1)
                //渲染数据
                renderRoomInfo(roomInfo)
            }
        }
    })
}


//下拉查询房间类型
function changeType() {

    const typeId = $("#changeType1").val()

    //编写SQL语句 需要一个最小的年龄和最大的年龄
    let number = 0;
    switch (typeId) {
        case '1':
            number = 1;
        break;
        case '2':
            number = 2;
        break;
        case '3':
            number = 3;
        break;
        case '4':
            number = 4;
        break;
        case '5':
            number = 5;
        break;
        case '6':
            number = 6;
        break;
        case '7':
            number = 7;
        break;
        // case '8':
        //     number = [1,2,3,4,5,6,7];
        // break;
    }
    Ajax({
        url: "http://localhost/hotel/php/roomFindType.php",
        data: { number },
        success(msg) {
            //将数据存储到Storage里面
            sessionStorage.setItem("roomInfo", msg)
            //将msg转化对象
            let roomInfo = JSON.parse(msg)
            //获取前10条数据
            roomInfo = roomInfo.slice(0, 10)
            //当前页是第一页
            sessionStorage.setItem("pageCurrent", 1)
            //渲染数据
            renderRoomInfo(roomInfo)
        }
    })
}